//
//  PlayerViewController.m
//  IntroductionApp
//
//  Created by bravesoft on 11/08/15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PlayerViewController.h"

#import "MDAudioFile.h"
#import "DownloadAlertView.h"
#import "ASIHTTPRequest.h"
#define kDownLoadAlertViewTag    2131


#define kKeyFileName            @"name"
#define kKeyFileURL             @"url"
@implementation PlayerViewController
@synthesize musicPlayer;
@synthesize ApiRequest;

- (void)initMusicsInfoData{
      
    NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:   [IntroAPPUtil getMusicFilesFolderPath] error:nil] ];
    
    for (int i =0; i < [array count]; i++) {
        NSString *fileName = [array objectAtIndex:i];
        fileName =[NSString stringWithFormat:@"%@%@",[IntroAPPUtil getMusicFilesFolderPath],fileName];
        [array replaceObjectAtIndex:i withObject:fileName];
    }
    
    NSMutableArray *songsArray = [[NSMutableArray alloc] init];
    for (NSString *songPath in array) {
        MDAudioFile *audioFile = [[MDAudioFile alloc] initWithPath:[NSURL fileURLWithPath:songPath]];
        [songsArray addObject:audioFile];
    }

    if ([songsArray count] > 0) {
        musicPlayer = [[MDAudioPlayerController alloc] initWithSoundFiles:songsArray atPath:[[NSBundle mainBundle] bundlePath] andSelectedIndex:0];

        [self.view addSubview:musicPlayer.view];
    }

}


#pragma mark- Class methods
- (void)dealloc
{
    [musicPlayer release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - DownLoad View  
- (void)showDownloadAlertView{
    DownloadAlertView *alertview = [[DownloadAlertView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    alertview.tag = kDownLoadAlertViewTag;
    [self.view addSubview:alertview];
    [alertview release];
}

- (void)removeDownLoadAlertView{
    UIView *alertView = [self.view viewWithTag:kDownLoadAlertViewTag];
    if (alertView) {
        [alertView removeFromSuperview];
    }
}

- (void)updataCheck{
    if([ IntroAPPUtil isNetworkState ]){
        // news
        self.ApiRequest = [[ SAConnectedApi alloc ]init];
        self.ApiRequest.Delegate = self;
        [ self.ApiRequest getMusicFileList ];
    }else{
        [self removeDownLoadAlertView]; //updata finished
        [self initMusicsInfoData];
    }
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([DefaultUril getNowSoundVersion] < [DefaultUril getLastSoundVersion]) {
        [self showDownloadAlertView];
        [self updataCheck];
    }else{
        [self initMusicsInfoData];
    }    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)downloadMusicFileByArray:(NSArray *)musicFilesArray{
    for (NSDictionary *musicInfoDic in musicFilesArray) {
        NSString *fileName = [musicInfoDic objectForKey:kKeyFileName];
        NSString *fileURLStr = [musicInfoDic objectForKey:kKeyFileURL];
        NSLog(@"URL:%@",fileURLStr);
        NSString *savePath = [NSString stringWithFormat:@"%@%@",[IntroAPPUtil getMusicFilesFolderPath],fileName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
            continue;
//            [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
        }else{
        
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:fileURLStr]];
            [request setDownloadDestinationPath:savePath];
            [request startSynchronous]; 
        }
        
    }
    [self removeDownLoadAlertView];
    [self initMusicsInfoData];
    [DefaultUril setNowSoundVersion:[DefaultUril getLastSoundVersion]];
}
#pragma mark - API Delegate
- (void)requestFinished:(SAConnectedApi*)object:(NSString*)request{
    NSArray *musicFilesArray = [request objectFromJSONString];
    if ([musicFilesArray count]>0 && musicFilesArray != nil) {
        [self downloadMusicFileByArray:musicFilesArray];
    }else{
        [self removeDownLoadAlertView]; //updata finished
        [self initMusicsInfoData];
    }
}

- (void)requestFailed:(SAConnectedApi*)object:(NSError*)error{
    NSLog(@"failed:%@",[error description]);
    [self removeDownLoadAlertView]; //updata finished
    [self initMusicsInfoData];
}

@end